package com.ec.auth.security.handle;

import com.ec.auth.datasource.DynamicDataSourceContextHolder;
import com.ec.auth.manager.AsyncManager;
import com.ec.auth.manager.factory.AsyncFactory;
import com.ec.common.constant.Constants;
import com.ec.common.core.domain.AjaxResult;
import com.ec.common.core.domain.model.LoginBody;
import com.ec.common.utils.MessageUtils;
import com.ec.common.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class FailHandle implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        LoginBody loginBody = (LoginBody) request.getAttribute("LoginBody");
        String exceptionMessage = exception.getMessage();
        if (exceptionMessage.equals("用户名或密码错误")) exceptionMessage = "user.password.not.match";
        String type = exceptionMessage.split("\\.")[0];

        String message;
        if (type.equals("tenant")) {
            message = MessageUtils.message(exceptionMessage, request.getHeader("tenant"));
        } else {
            // 记录日志数据
            message = MessageUtils.message(exceptionMessage, loginBody.getUsername());
        }

        // 请求结束删除localThread
        DynamicDataSourceContextHolder.clearDataSourceKey();
        AsyncManager.me().execute(AsyncFactory.recordLoginInfo(loginBody.getUsername(), Constants.LOGIN_FAIL,
                message));
        ServletUtils.renderFailString(response, AjaxResult.error(message));
    }
}
